<template>
	<view class="body" style="min-height: 1400rpx;">
		<!-- 商品图片 -->
		<view>
			<swiper style="height: 600rpx;" circular indicator-dots="true" autoplay="true" :interval="3000"
				duration="2000">
				<swiper-item v-for="(item,index) in goodsDetail.goods_banner_imgs">
					<view>
						<image style="height: 600rpx;width:100%;" :src="item.url" mode="scaleToFill" />
					</view>
				</swiper-item>
			</swiper>
		</view>

		<!-- 商品详细信息 -->
		<view class="outer-box" style="height: 300rpx;margin-top: 20rpx;position: relative;">
			<view>
				<view style="display: flex;align-items: center;margin-left: 15rpx;">
					<text class="price-font">
						<text class="yuan-font">￥</text>
						<text style=" font-size: 40rpx;">
							{{convert(goodsDetail.goods_price).integer}}
						</text>
						.
						<text style="font-size: 32rpx;">
							{{convert(goodsDetail.goods_price).point}}
						</text>
					</text>
					<view style="width: 20rpx;"></view>
				</view>
				<view class="goods-name-box">
					{{goodsDetail.name}}
				</view>
				<view class="goods-desc-box">
					{{goodsDetail.goods_desc}}
				</view>
			</view>
		</view>

		<!-- 底部栏 -->
		<view class="btm">
			<view class="goods-carts">
				<uni-goods-nav :options="options" :fill="true" :button-group="buttonGroup" @click="onClick"
					@buttonClick="buttonClick" />
			</view>
		</view>

		<view>
			<hb-comment ref="hbComment" @add="add" @del="del" @like="like" @focusOn="focusOn" :deleteTip="'确认删除？'"
				:cmData="commentData" v-if="commentData"></hb-comment>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database();

	export default {
		data() {
			return {
				goodsDetail: 0,
				goodsListIds: [],
				options: [{
					icon: 'chat',
					text: '客服'
				}, {
					icon: 'shop',
					text: '店铺',
					infoBackgroundColor: '#007aff',
					infoColor: "#f5f5f5"
				}],
				buttonGroup: [{
					text: '立即出售同款',
					backgroundColor: 'linear-gradient(90deg, #9be8e8, #5bcde6)',
					color: '#fff'
				}],
				telephone: 17773776617,
				address: 'p j y',
				goods_id: '',
				commentData: null,
				commentReq: {
					"pId": null, // 评论父id
					"content": null // 评论内容
				},
				commentList: [],
			}
		},
		onLoad(option) {
			this.goodsDetail = JSON.parse(decodeURIComponent(option.item))
			this.goods_id = this.goodsDetail._id

			this.readNumer()
			this.initComment()
			this.getShopInformation()
		},
		methods: {
			convert(money) {
				return {
					integer: Math.floor(money / 100),
					point: money % 100
				}
			},
			onClick(e) {
				console.log(e)
				if (e.index == 0) {
					uni.showModal({
						title: '联系电话',
						content: '' + this.telephone,
						showCancel: false
					})
				} else if (e.index == 1) {
					uni.showModal({
						title: '店铺地址',
						content: '' + this.address,
						showCancel: false
					})
				}
			},
			async getShopInformation() {
				let res = await db.collection('business-information').limit(1).get()
				this.telephone = res.result.data[0].telephone
				this.address = res.result.data[0].shop_address
			},
			async buttonClick(e) {
				console.log(e)
				if (e.index == 0) {
					const goods = uniCloud.importObject("goods")
					let res = await goods.getById(this.goods_id)
					uni.navigateTo({
						url: '/pages/order/order?goods=' + encodeURIComponent(JSON.stringify(res[0]))
					})
				}
			},
			async initComment() {
				const db = uniCloud.database()
				let res1 = await db.collection('comment,uni-id-users').where({
						"goods_id": this.goods_id
					}).field(
						'nickname,create_date,like_ids,content,user_id.nickname,user_id.avatar_file,user_id._id,parent_id,_id'
					)
					.orderBy(
						'create_date', 'asc')
					.get()
				res1.result.data.forEach(item => {
					item['id'] = item._id
					item['hasLike'] = item.like_ids.includes(uniCloud.getCurrentUserInfo().uid)
					item['likeNum'] = item.like_ids.length
					item['nickName'] = item.user_id[0].nickname
					item['createTime'] = this.formatDate(item.create_date)
					item['parentId'] = item.parent_id
					item['avatarUrl'] = item.user_id[0].avatar_file == null ? '' : item.user_id[0].avatar_file
						.url
				})
				this.commentList = res1.result.data
				let res2 = await db.collection('goods_page_view').where({
					'goods_id': this.goods_id
				}).get()
				let redNum = res2.result.data[0] == null ? 1 : res2.result.data[0].read_num
				this.commentData = {
					"readNumer": redNum,
					"commentSize": this.commentList.length,
					"comment": this.getTree(this.commentList)
				}
			},
			getTree(data) {
				let result = [];
				let map = {};
				data.forEach(item => {
					map[item.id] = item;
				});
				data.forEach(item => {
					let parent = map[item.parentId];
					if (parent) {
						(parent.children || (parent.children = [])).push(item);
					} else {
						result.push(item);
					}
				});
				return result;
			},
			// 新增评论
			async add(commentReq) {
				const db = uniCloud.database();
				await db.collection('comment').add({
					goods_id: this.goods_id,
					user_id: uniCloud.getCurrentUserInfo().uid,
					content: commentReq.content,
					parent_id: commentReq.pId,
					like_ids: [],
					status: 1
				})
				this.$refs.hbComment.addComplete()
				// 新增完成
				uni.showModal({
					content: '发表成功',
					showCancel: false
				});
				setTimeout(() => {
					// location.reload()
					uni.redirectTo({
						url: '/pages/details/details?item=' + encodeURIComponent(JSON.stringify(this
							.goodsDetail))
					})
				}, 1000)
			},
			//点赞
			async like(comment_id) {
				let hasLike = false
				this.commentList.forEach(item => {
					if (item.id == comment_id) {
						hasLike = item.hasLike
					}
				})
				if (hasLike) {
					uni.showModal({
						content: '不能重复点赞~',
						showCancel: false
					});
					return
				}
				uni.showLoading({
					mask: true,
					title: '加载中...'
				})
				const comment = uniCloud.importObject("comment")
				let count = await comment.like(comment_id, uniCloud.getCurrentUserInfo().uid)
				setTimeout(() => {
						uni.hideLoading()
						uni.redirectTo({
							url: '/pages/details/details?item=' + encodeURIComponent(JSON.stringify(this
								.goodsDetail))
						})
					},
					1000)
			},
			del(commentId) {
				this.$refs.hbComment.deleteComplete(commentId)
			},
			// 输入框失去焦点
			blur() {
				this.$refs.hbComment.blur()
			},
			formatDate(stampTime) {
				const myDate = new Date(stampTime);
				const Y = myDate.getFullYear();
				const M = myDate.getMonth() + 1;
				const D = myDate.getDate();
				const h = myDate.getHours()
				const m = myDate.getMinutes()
				const dateTime = Y + '-' + M + '-' + D + ' ' + h + ':' + m
				return dateTime
			},
			focusOn() {},
			async readNumer() {
				const comment = uniCloud.importObject("comment")
				await comment.addReadNum(this.goods_id)
			}
		},
	}
</script>

<style scoped>
	.btm {
		position: fixed;
		z-index: 99;
		width: 100%;
		height: 100rpx;
	}

	.goods-carts {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		position: fixed;
		left: 0;
		right: 0;
		/* #ifdef H5 */
		left: var(--window-left);
		right: var(--window-right);
		/* #endif */
		bottom: 0;
	}

	.goods-desc-box {
		margin-top: 15rpx;
		margin-left: 15rpx;
		font-size: 30rpx;
		overflow: hidden;
		height: 40rpx;
		width: 95%;
		text-overflow: ellipsis;
		color: #7c7c7c;
	}

	.goods-name-box {
		margin-top: 15rpx;
		margin-left: 15rpx;
		font-size: 30rpx;
		font-weight: bold;
	}

	.label-anxingou {
		background: rgb(255, 85, 0);
		width: 156rpx;
		height: 50rpx;
		border-radius: 18rpx;
		line-height: 50rpx;
		text-align: center;
	}

	.label-desc {
		width: 88%;
		height: 56rpx;
		background-color: rgb(255, 228, 208);
		border: rgb(240, 202, 182) 1px solid;
		position: absolute;
		bottom: 40rpx;
		margin-left: 6%;
		border-radius: 18rpx;
		color: rgb(255, 192, 137);
		text-align: center;
		line-height: 56rpx;
	}
</style>